package linkedlist;


/**
 * Created with IntelliJ IDEA.
 * Description: 203.移除链表元素
 * User: Li_yizYa
 * Date: 2025—03—24
 * Time: 15:11
 */


public class Solution1 {

    public static void main(String[] args) {

        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(6);
        ListNode node4 = new ListNode(3);
        ListNode node5 = new ListNode(4);
        ListNode node6 = new ListNode(5);
        ListNode node7 = new ListNode(6);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;
        node7.next = null;

        ListNode head = removeElement(node1, 6);
        while (head != null) {
            System.out.print(head.val + " ");
            head = head.next;
        }
    }

    public static ListNode removeElement(ListNode head, int val) {
        if (head == null) {
            return head;
        }

        head.next = removeElement(head.next, val);
        if (head.val == val) {
            return head.next;
        }
        return head;
    }
    /**
     * 非递归实现
     * @param head
     * @param val
     * @return
     */
    public static ListNode removeElement1(ListNode head, int val) {
        //判断链表是否为空
        if (head == null) {
            return head;
        }
        //判断头结点是否为要删除的结点并删除
        while (head != null && head.val == val) {
            head = head.next;
        }
        //删除其余等于val的结点
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            if (cur.next.val != val) {
                cur = cur.next;
            } else {
                cur.next = cur.next.next;
            }
        }
        return head;
    }
}
